<template>
  <div class="min-h-screen bg-gray-50 flex flex-col py-12 sm:px-6 lg:px-8">
    <div class="sm:mx-auto sm:w-full sm:max-w-md">
      <!-- 测试提示 -->
      <!-- <div class="bg-blue-50 border border-blue-200 rounded-md p-4 mb-4">
        <div class="flex">
          <div class="flex-shrink-0">
            <svg class="h-5 w-5 text-blue-400" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"></path>
            </svg>
          </div>
          <div class="ml-3">
            <h3 class="text-sm font-medium text-blue-800">测试账号</h3>
            <div class="mt-2 text-sm text-blue-700">
              <p>手机号：13800138000</p>
              <p>验证码：123456</p>
            </div>
          </div>
        </div>
      </div> -->

      <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
        <form class="space-y-6" @submit.prevent="handleSubmit">
          <!-- 手机号输入 -->
          <div>
            <label for="phone" class="block text-sm font-medium text-gray-700 mb-2">
              手机号
            </label>
            <input
              id="phone"
              v-model="form.phone"
              type="tel"
              autocomplete="tel"
              placeholder="请输入手机号"
              required
              maxlength="11"
              class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-400 text-gray-900 bg-white focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
            />
          </div>

          <!-- 验证码输入 -->
          <div>
            <label for="code" class="block text-sm font-medium text-gray-700 mb-2">
              验证码
            </label>
            <div class="flex space-x-2">
              <input
                id="code"
                v-model="form.code"
                type="text"
                autocomplete="one-time-code"
                placeholder="请输入验证码"
                required
                maxlength="6"
                class="flex-1 appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-400 text-gray-900 bg-white focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
              />
              <button
                type="button"
                @click="sendCode"
                :disabled="countdown > 0 || !form.phone"
                class="px-4 py-2 bg-blue-500 text-white text-sm font-medium rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
              </button>
            </div>
          </div>

          <!-- 协议同意 -->
          <div class="flex items-center">
            <input
              id="agree"
              v-model="form.agree"
              type="checkbox"
              class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
            <label for="agree" class="ml-2 block text-sm text-gray-900">
              同意
              <a href="/electronic-signature-authorization" class="text-blue-600 hover:text-blue-500">《电子签章申请及使用授权书》</a>
            </label>
          </div>

          <!-- 提交按钮 -->
          <div>
            <button
              type="submit"
              :disabled="!canSubmit"
              class="w-full flex justify-center py-3 px-4 border border-transparent rounded-full text-sm font-medium text-white bg-blue-500 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              提交
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useApi } from '~/utils/apiConfig'

const route = useRoute()
const { showSuccess, showError } = useToast()
const runtimeConfig = useRuntimeConfig()

const REDIRECT_STORAGE_KEY = 'freelancer_redirect_url'
const WECHAT_STATE_STORAGE_KEY = 'freelancer_wechat_oauth_state'
const WEIXIN_LOGIN_PATH = '/weixin-login'

// 表单数据
const form = ref({
  phone: '',
  code: '',
  agree: false
})

// 倒计时
const countdown = ref(0)
const timer = ref(null)

// API 实例
const api = useApi('freelancer')

// 计算属性
const canSubmit = computed(() => {
  return form.value.phone &&
         form.value.code &&
         form.value.agree &&
         form.value.phone.length === 11 &&
         form.value.code.length === 6
})

const isWeChatBrowser = () => {
  if (typeof navigator === 'undefined') {
    return false
  }
  return /micromessenger/i.test(navigator.userAgent)
}

const createState = () => {
  if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
    return crypto.randomUUID().replace(/-/g, '')
  }
  return Math.random().toString(36).slice(2, 12)
}

const triggerWeChatOAuth = () => {
  if (typeof window === 'undefined') {
    console.log("triggerWeChatOAuth returned");
    return
  }

  const appId = runtimeConfig.public.WECHAT_OFFICIAL_ACCOUNT_APPID
  if (!appId) {
    console.warn('WECHAT_OFFICIAL_ACCOUNT_APPID is not configured; skip WeChat OAuth redirect.')
    return
  }

  const state = createState()
  localStorage.setItem(WECHAT_STATE_STORAGE_KEY, state)

  const redirectUri = `${window.location.origin}${WEIXIN_LOGIN_PATH}`
  console.log(window.location.origin);
  console.log(redirectUri);
  const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`
  window.location.replace(authUrl)
}

const ensureWeChatOAuth = () => {
  if (!isWeChatBrowser()) {
    console.log("isWeChatBrowser false");
    return
  }

  if (localStorage.getItem('userToken')) {
    console.log("userToken got");
    return
  }

  if (typeof window === 'undefined') {
    console.log("window === undefined");
    return
  }

  if (window.location.pathname !== '/login') {
    return
  }

  triggerWeChatOAuth()
}

const resolveRedirectUrl = () => {
  const storedRedirect = localStorage.getItem(REDIRECT_STORAGE_KEY)
  if (storedRedirect) {
    localStorage.removeItem(REDIRECT_STORAGE_KEY)
    return storedRedirect
  }

  const queryRedirect = typeof route.query.redirect === 'string' ? route.query.redirect : null
  return queryRedirect || '/profile'
}

onMounted(() => {
  if (typeof window === 'undefined') {
    return
  }

  const queryRedirect = typeof route.query.redirect === 'string' ? route.query.redirect : null
  if (queryRedirect) {
    localStorage.setItem(REDIRECT_STORAGE_KEY, queryRedirect)
  }

  ensureWeChatOAuth()
})

// 发送验证码
const sendCode = async () => {
  if (!form.value.phone || form.value.phone.length !== 11) {
    showError('请输入正确的手机号')
    return
  }

  try {
    const response = await api.post('/send-sms-code', {
      phone: form.value.phone
    })

    if (response.code === 0) {
      // 开始倒计时
      countdown.value = 60
      timer.value = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer.value)
        }
      }, 1000)

      if (response.data.test_code) {
        showSuccess(`测试验证码：${response.data.test_code}`)
      } else {
        showSuccess('验证码已发送')
      }
    } else {
      showError(response.message || '发送验证码失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    showError('发送验证码失败，请重试')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!canSubmit.value) return

  try {
    const response = await api.post('/login', {
      phone: form.value.phone,
      code: form.value.code
    })

    if (response.code === 0) {
      // 保存用户信息到本地存储
      localStorage.setItem('userToken', response.data.token)
      localStorage.setItem('userInfo', JSON.stringify(response.data.user))

      showSuccess('登录成功！')

      const redirectUrl = resolveRedirectUrl()
      await navigateTo(redirectUrl)
    } else {
      showError(response.message || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    showError('登录失败，请检查验证码是否正确')
  }
}

// 清理定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
</script>
